package com.prj.util;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.net.SSLContextBuilder;
import cn.hutool.core.util.IdUtil;
import cn.hutool.db.Db;
import cn.hutool.db.Entity;
import cn.hutool.http.HtmlUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class HttpRequestUtils {
	
	public static String invokeHttpForm(String url, Map<String, Object> param) {
		return invokeHttpForm(url, param, null);
	}
	
	public static String invokeHttpForm(String url, Map<String, Object> param, Map<String, String> headers) {
		try {
			log.info("调用接口：{}, 参数：{}", url, JSONUtil.toJsonStr(param));
			HttpRequest post = HttpRequest.post(url);
			if(HttpUtil.isHttps(url)) {
				post.setSSLSocketFactory(SSLContextBuilder.create().buildChecked().getSocketFactory());
			}
			if (MapUtil.isNotEmpty(headers)) {
				post.addHeaders(headers);
			}
			String body = post.form(param).execute().body();
			log.info("调用结果：{}", body);
			return body;
		} catch (Exception e) {
			e.printStackTrace();
			log.info("接口调用异常：{}, 参数：{}, 异常：{}", url, JSONUtil.toJsonStr(param), e);
		}
		return null;
	}
	
	public static String invokeHttp(String url, String json) {
		return invokeHttp(url, json, null);
	}
	
	public static String invokeHttp(String url, String json, Map<String, String> headers) {
		try {
			log.info("调用接口：{}, 参数：{}", url, json);
			HttpRequest post = HttpRequest.post(url);
			if(HttpUtil.isHttps(url)) {
				post.setSSLSocketFactory(SSLContextBuilder.create().buildChecked().getSocketFactory());
			}
			if (MapUtil.isNotEmpty(headers)) {
				post.addHeaders(headers);
			}
			String body = post.body(json) .execute().body();
			//log.info("调用结果：{}", body);
			return body;
		} catch (Exception e) {
			e.printStackTrace();
			log.info("接口调用异常：{}, 参数：{}, 异常：{}", url, json, e);
		}
		return null;
	}
	
	public static void exportExcel(String filePath, JSONArray jsonArray) {
        ExcelWriter writer = ExcelUtil.getWriter(FileUtil.file(filePath));
        List<String> headers = null;
        if (jsonArray.size() > 0) {
            JSONObject firstObj = jsonArray.getJSONObject(0);
            headers = new ArrayList<>(firstObj.keySet());
            writer.writeHeadRow(headers); // 写入表头行
        }else {
        	System.out.println("未找到导出数据！");
        	return;
        }
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject obj = jsonArray.getJSONObject(i);
            List<Object> rowData = new ArrayList<>();
            for (String key : headers) {
                rowData.add(obj.get(key));
            }
            writer.writeRow(rowData);
        }
        writer.close();
        System.out.println("导出完成！");
	}
	
	public static void exportExcels(String filePath, List<JSONArray> list, String... sheetNames) {
        try (ExcelWriter writer = new ExcelWriter(filePath, sheetNames[0])) {
            for (int i = 0; i < list.size(); i++) {
                JSONArray array = list.get(i);
                String sheetName = "Sheet" + (i + 1);
                if(list.size() == sheetNames.length) {
                	sheetName = sheetNames[i];
                }
                writer.setSheet(sheetName);
                if (!array.isEmpty()) {
                    writer.writeHeadRow(array.getJSONObject(0).keySet());
                }
                writer.write(array);
            }
            System.out.println("导出完成！");
        }
	}
	
	public static JSONObject buildCwQuery(String dict, JSONObject whereCondition) {
		JSONObject data = new JSONObject();
		data.set("ACCESSKEY", "5348e141-cb9a-465b-3c68-7ad03478d5d9");
		data.set("SECRETKEY", "b0c2cb18-3be8-3327-30f0-fb662dbe2862");
		data.set("appInstanceCode", "1000");
		data.set("unitCode", "010218");
		data.set("sourceSystem", "YC-GDY");
		data.set("dicCode", dict);
		data.set("whereCondition", whereCondition);
		return data;
	}
	
	public static JSONObject buildMdmData(JSONArray datas) {
		JSONObject data = new JSONObject();
		JSONObject ESB = new JSONObject();
		JSONObject DATA = new JSONObject();
		JSONObject DATAINFOS = new JSONObject();
		DATAINFOS.set("DATAINFO", datas);
		DATAINFOS.set("PUUID", IdUtil.simpleUUID());
		DATA.set("DATAINFOS", DATAINFOS);
		ESB.set("DATA", DATA);
		data.set("ESB", ESB);
		return data;
	}
	
	public static JSONObject buildMdmQuery(JSONObject whereCondition) {
		JSONObject data = new JSONObject();
		JSONObject ESB = new JSONObject();
		JSONObject DATA = new JSONObject();
		JSONObject DATAINFOS = new JSONObject();
		JSONArray DATAINFO = new JSONArray();
		JSONObject SPLITPAGE = new JSONObject();
		DATAINFO.add(whereCondition);
		DATAINFOS.set("DATAINFO", DATAINFO);
		//DATAINFOS.set("PUUID", IdUtil.simpleUUID());
		DATA.set("DATAINFOS", DATAINFOS);
		SPLITPAGE.set("COUNTPERPAGE", whereCondition.get("limit"));
		SPLITPAGE.set("CURRENTPAGE", whereCondition.get("page"));
		DATA.set("SPLITPAGE", SPLITPAGE);
		ESB.set("DATA", DATA);
		data.set("ESB", ESB);
		return data;
	}
	
	
	public static void main(String[] args) throws Exception{
		
// =========================================UIM查询=========================================================
//		Map<String, Object> param = new HashMap<String, Object>();
//		param.put("userId", "MDM");
//		param.put("password", "mdm2022@GEDI");
//		param.put("realmId", "$IDM");
//        String tokenBody = invokeHttpForm("https://uim.gedi.com.cn/am5/rest/authn/login", param);
//		String sessionToken = JSONUtil.parseObj(tokenBody).getJSONObject("result").getStr("sessionToken");
//		
//		param = new HashMap<String, Object>();
//		param.put("sessionToken", sessionToken);
//		param.put("modifiedTime_gt", "2022-01-01 00:00:00.000");
//		param.put("serviceId", "MDM");
//		String ryBody = invokeHttpForm("https://uim.gedi.com.cn/uimapi/AccountServlet", param);
//		JSONArray jsonArray = JSONUtil.parseObj(ryBody).getJSONArray("data");
//		exportExcel("D:/output.xlsx", jsonArray);
		
		
		
// =========================================财务查询=========================================================
//		JSONObject where = new JSONObject();
//		where.set("starttime", "2022-06-08T02:21:37.366+08:00");
//		where.set("endtime", "2023-06-28T02:21:37.366+08:00");
//		where.set("PageNum", 1);
//		JSONObject data = buildCwQuery("IndustryClassificationQuery", where);
//		JSONArray array = new JSONArray();
//		String body = invokeHttp("http://esb.ceec.net.cn:8280/CEEC_CWYTH_CW_QueryData", data.toString());
//		JSONObject result = JSONUtil.parseObj(body);
//		Integer maxpage = result.getInt("TotalPage");
//		array.addAll(result.getJSONArray("data"));
//		for(int i = 2; i <= maxpage; i++) {
//			where.set("PageNum", i);
//			body = invokeHttp("http://esb.ceec.net.cn:8280/CEEC_CWYTH_CW_QueryData", data.toString());
//			array.addAll(JSONUtil.parseObj(body).getJSONArray("data"));
//		}
//		exportExcel("D:/hyfl.xlsx", array);
		
		
// =========================================推送MDM=========================================================
//		JSONArray datas = new JSONArray();
//		JSONObject obj = new JSONObject();
//		obj.set("id", "2");
//		obj.set("username", "g1800");
//		datas.add(obj);
//		JSONObject data = buildMdmData(datas);
//		HashMap<String, String> newHashMap = MapUtil.newHashMap();
//		newHashMap.put("usercode", "admin");
//		newHashMap.put("password", "1");
//		invokeHttp("http://10.150.201.132/esbmule/services/receive/FROM_PUSH_TEST", data.toString(), newHashMap);
		
		
// =========================================查询MDM=========================================================
//		JSONObject where = new JSONObject();
//		where.set("page", 1);
//		where.set("limit", 50);
//		HashMap<String, String> newHashMap = MapUtil.newHashMap();
//		newHashMap.put("usercode", "inf_zdsj");
//		newHashMap.put("password", "Sa209Te!");
//		JSONObject data = buildMdmQuery(where);
//		String result = invokeHttp("http://10.150.201.132/esbmule/services/query/P_QUERY_GJDQ", data.toString(), newHashMap);
//		JSONObject body = JSONUtil.parseObj(result);
//		JSONObject split = body.getByPath("ESB.DATA.SPLITPAGE", JSONObject.class);
//		JSONArray datas = body.getByPath("ESB.DATA.DATAINFOS.DATAINFO", JSONArray.class);
//		JSONArray array = new JSONArray();
//		array.addAll(datas);
//		Integer totalPage = split.getInt("TOTALPAGES");
//		for(int i = 2; i <= totalPage; i++) {
//			where.set("page", i);
//			result = invokeHttp("http://10.150.201.132/esbmule/services/query/P_QUERY_GJDQ", data.toString(), newHashMap);
//			array.addAll(JSONUtil.parseObj(result).getByPath("ESB.DATA.DATAINFOS.DATAINFO", JSONArray.class));
//		}
//		exportExcel("D:/gjdq.xlsx", array);
		
		
// =========================================导出模型=========================================================
//		Db db = Db.use("mdmprd");
//		List<Entity> list = db.find(Entity.create("mdm_syscode"));
//		String cookie = "Security=HttpOnly; SUNWAY_LOCALE=zh_CN; LAYOUT={%22showSidebar%22:false%2C%22showHeader%22:true%2C%22fontSize%22:12%2C%22theme%22:%22chalk%22}; SUNWAY_JWT=eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJhZG1pbkAxMC4xMjIuOTUuOThAMTc1NDQ0NjMyOTY2NyIsImF1ZCI6ImFkbWluQHpoX0NOQHN1bndheTZA6LaF57qn566h55CG5ZGYIiwiaXNzIjoic3Vud2F5IiwiZXhwIjoxNzU0NTE4MzI5NjY3LCJpYXQiOjE3NTQ0NDYzMjk2NjcsImp0aSI6IjEifQ.m0uQhtnSLJB4rBRZ_RK47ar-UkVLDTPZShQh7r2hb_w";
//		for (Entity entity : list) {
//			String syscode = entity.getStr("syscode");
//			String codename = entity.getStr("codename");
//			String dir = "";
//			switch (entity.getStr("syscodetype")) {
//			case "242814566004690409":
//				dir = "参考数据";
//				break;
//			case "242814566004690410":
//				dir = "业务数据";
//				break;
//			case "242814566004690405":
//				dir = "主数据";
//				break;
//			default:
//				break;
//			}
//			HttpRequest.get("http://dataplatform.gedi.com.cn/module/module/export/propdata?tablecode="+syscode+"&checkedExcelType=2007&mdmlanguage=zh_CN&locale=zh_CN")
//			           .form("excelType", "2007")
//			           .cookie(cookie)
//			           .execute()
//			           .writeBody("E:\\projectManage\\GEDI\\模型备份\\" + dir + "\\" + syscode +"-" + codename + ".xlsx");
//		}
//		System.out.println("finished");
		
		
// =========================================增加子公司接口权限=========================================================
//		Db db = Db.use("mdmdev");
//		List<Entity> list = db.query("SELECT b.RECEIVEID, b.SYNCODE, b.SYNNAME  FROM ESB_MULE_RECEIVEUSER a inner JOIN ESB_MULE_RECEIVE b ON a.RECEIVEID = b.RECEIVEID "
//				+ "WHERE a.USERCODE = 'inf_tz'");
//		String cookie = "Security=HttpOnly; SUNWAY_JWT=eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJhZG1pbkAxMC4xMjIuOTUuOThAMTc1MjcxMzgxMzE2OSIsImF1ZCI6ImFkbWluQHpoX0NOQHN1bndheTZA6LaF57qn566h55CG5ZGYIiwiaXNzIjoic3Vud2F5IiwiZXhwIjoxNzUyNzg1ODEzMTY5LCJpYXQiOjE3NTI3MTM4MTMxNjksImp0aSI6IjEifQ.9D9dVN_BDup-hZuzvTiz5DVFIFYE5gZ8KPQ_FlDbVuQ; SUNWAY_LOCALE=zh_CN; LAYOUT={%22showSidebar%22:false%2C%22showHeader%22:true%2C%22fontSize%22:12%2C%22theme%22:%22chalk%22}";
//		String requestToken = "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJhZG1pbkAxMC4xMjIuOTUuOThAMTc1MjcxMzgxMzE2OSIsImF1ZCI6ImFkbWluQHpoX0NOQHN1bndheTZA6LaF57qn566h55CG5ZGYIiwiaXNzIjoic3Vud2F5IiwiZXhwIjoxNzUyNzg1ODEzMTY5LCJpYXQiOjE3NTI3MTM4MTMxNjksImp0aSI6IjEifQ.9D9dVN_BDup-hZuzvTiz5DVFIFYE5gZ8KPQ_FlDbVuQ";
//		String url = "http://10.150.201.132/esbmule/esbmule/receive/startReceiveMuleInfo";
//		for(Entity en : list) {
//			Long id = db.queryOne("SELECT seq_esb.nextval id FROM dual").getLong("id");
//			Long interfaceId =  en.getLong("RECEIVEID");
//			db.insertOrUpdate(Entity.create("ESB_MULE_RECEIVEUSER").set("RECEIVEUSERID", id)
//					.set("RECEIVEID", interfaceId)
//					.set("USERCODE", "inf_tc")
//					.set("PASSWORD", "1")
//					.set("RECORDERCODE", "admin")
//					.set("RECORDERDESC", "超级管理员")
//					.set("RECORDTIME", new Date()),
//					"RECEIVEID", "USERCODE"
//					);
//			//禁用接口
//			HttpRequest.post(url)
//			.cookie(cookie)
//			.header("x-requested-token", requestToken)
//			.body("{  \"cond.receiveid\": \""+interfaceId+"\",  \"cond.releaseflag\": \"0\",  \"cond.freezeflag\": \"0\",  \"cond.freezereason\": \"\"}")
//			.execute();
//			//启用接口
//			HttpRequest.post(url)
//			.cookie(cookie)
//			.header("x-requested-token", requestToken)
//			.body("{  \"cond.receiveid\": \""+interfaceId+"\",  \"cond.releaseflag\": \"1\"}")
//			.execute();
//		}
		
// =========================================创建虚拟项目与合同=========================================================
//		String url = "http://10.150.201.132/esbmule/services/receive/";
//		String usercode = "inf_tz";
//		String password = "1";
//		String orgcode = "14";
//		String orgname = "德泰公司接口认证用户";
//		HttpRequest.post(url+"XM_ALL")
//        .header("usercode", usercode)
//        .header("password", password)
//        .body("{\"ESB\":{\"DATA\":{\"DATAINFOS\":{\"DATAINFO\":[{\"CODE\":\"010218p202100000("+orgcode+")\",\"DESC21\":\""+orgname+"\",\"DESC1\":\"中国能源建设集团广东省电力设计研究院有限公司虚拟项目\",\"DESC100\":\"上报成功\",\"DESC23\":\"2024-04-23\",\"DESC26\":\"承接项目\",\"DESC38\":\"010218p202100002\",\"DESC45\":\"组织私有\",\"DESC55\":\"广东院主数据\",\"DESC56\":\"MDM\",\"DESC59\":\"否\"}]}}}}")
//        .execute();
//		
//		HttpRequest.post(url+"HT_ALL")
//		.header("usercode", usercode)
//		.header("password", password)
//		.body("{\"ESB\":{\"DATA\":{\"DATAINFOS\":{\"DATAINFO\":[{\"CODE\":\"010218c202200000("+orgcode+")\",\"DESC17\":\"010218p202100000("+orgcode+")\",\"DESC1\":\"中国能源建设集团广东省电力设计研究院有限公司虚拟合同\",\"DESC100\":\"上报成功\",\"DESC16\":\"中国能源建设集团广东省电力设计研究院有限公司虚拟项目\",\"DESC18\":\"中国能源建设集团广东省电力设计研究院有限公司\",\"DESC20\":\"中国能源建设集团广东省电力设计研究院有限公司\",\"DESC25\":\"2021-11-01\",\"DESC26\":\"2021\",\"DESC27\":\"2022-01-01\",\"DESC28\":\"2099-01-01\",\"DESC29\":\"否\",\"DESC30\":\"生效\",\"DESC31\":\"其他合同\",\"DESC33\":\"单价\",\"DESC34\":\"其他\",\"DESC4\":\"0.00\",\"DESC43\":\"虚拟预置\",\"DESC5\":\"0.00\",\"DESC56\":\"010218c202200000\",\"DESC60\":\"20QTHT\",\"DESC64\":\"010218p202100002\",\"DESC71\":\"广东院主数据\",\"DESC72\":\"MDM\",\"DESC77\":\"0.00\",\"DESC78\":\"CNY\",\"DESC79\":\"否\",\"DESC80\":\"0\"}]}}}}")
//		.execute();
		
// =========================================集团模型导出========================================================		
//		String cookie = "Security=HttpOnly; SUNWAY_LOCALE=zh_CN; LAYOUT={%22showSidebar%22:false%2C%22showHeader%22:true%2C%22fontSize%22:12%2C%22theme%22:%22chalk%22}; SUNWAY_JWT=eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIwMTAyMThBRzg0MDFAMTAuMTA5LjI1NS4yNTRAMTc1MjczMjkzMDcxNiIsImF1ZCI6IjAxMDIxOEFHODQwMUB6aF9DTkBzdW53YXk2QOiuuOWkmiIsImlzcyI6InN1bndheSIsImV4cCI6MTc1MjgwNDkzMDcxNiwiaWF0IjoxNzUyNzMyOTMwNzE2LCJqdGkiOiIxIn0.FrvspW2QS3vLEGLWbMFOZ2D_nAKjtZWFC-BfTkr-iTs";
//		String body = HttpRequest.post("https://mdm.ceec.net.cn/module/mdm/core/selectSyscodeInfoByCond")
//		.cookie(cookie)
//		.header("x-requested-token", "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIwMTAyMThBRzg0MDFAMTAuMTA5LjI1NS4yNTRAMTc1MjczMjkzMDcxNiIsImF1ZCI6IjAxMDIxOEFHODQwMUB6aF9DTkBzdW53YXk2QOiuuOWkmiIsImlzcyI6InN1bndheSIsImV4cCI6MTc1MjgwNDkzMDcxNiwiaWF0IjoxNzUyNzMyOTMwNzE2LCJqdGkiOiIxIn0.FrvspW2QS3vLEGLWbMFOZ2D_nAKjtZWFC-BfTkr-iTs")
//		.body("{\"cond.auditflag\":\"2\",\"jsonString\":\"{\\\"cond\\\":{}}\",\"page\":1,\"start\":0,\"limit\":500}")
//		.execute().body();
//		System.out.println(body);
//		JSONObject json = JSONUtil.parseObj(body);
//		System.out.println("模型数量===" + json.getInt("syscodeInfos_num"));
//		JSONArray jsonArray = json.getJSONArray("syscodeInfos");
//		for(int i = 0; i < jsonArray.size(); i++) {
//			JSONObject jsonObject = jsonArray.getJSONObject(i);
//			String syscode = jsonObject.getStr("syscode");
//			String codename = jsonObject.getStr("codename");
//			HttpRequest.get("https://mdm.ceec.net.cn/module/module/export/propdata?tablecode="+syscode+"&checkedExcelType=2007&mdmlanguage=zh_CN&locale=zh_CN")
//	           .form("excelType", "2007")
//	           .cookie(cookie)
//	           .execute()
//	           .writeBody("E:\\projectManage\\GEDI\\集团模型备份\\" + syscode + codename + ".xlsx");
//		}
		
// =========================================接口导出========================================================		
//		String server = "http://dataplatform.gedi.com.cn";
//		String server = "https://mdm.ceec.net.cn";
//		String cookie = "Security=HttpOnly; SUNWAY_JWT=eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIwMTAyMThBRzg0MDFAMTAuMTA5LjI1NS4yNTRAMTc1MzE3NTY4NjI1MiIsImF1ZCI6IjAxMDIxOEFHODQwMUB6aF9DTkBzdW53YXk2QOiuuOWkmiIsImlzcyI6InN1bndheSIsImV4cCI6MTc1MzI0NzY4NjI1MiwiaWF0IjoxNzUzMTc1Njg2MjUyLCJqdGkiOiIxIn0.thXSq9BuN219jQvQoHScIX5XnVf7K1FbdsDjRlAX2S8; SUNWAY_LOCALE=zh_CN; LAYOUT={%22showSidebar%22:false%2C%22showHeader%22:true%2C%22fontSize%22:12%2C%22theme%22:%22chalk%22}";
//		String token = "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIwMTAyMThBRzg0MDFAMTAuMTA5LjI1NS4yNTRAMTc1MzE3NTY4NjI1MiIsImF1ZCI6IjAxMDIxOEFHODQwMUB6aF9DTkBzdW53YXk2QOiuuOWkmiIsImlzcyI6InN1bndheSIsImV4cCI6MTc1MzI0NzY4NjI1MiwiaWF0IjoxNzUzMTc1Njg2MjUyLCJqdGkiOiIxIn0.thXSq9BuN219jQvQoHScIX5XnVf7K1FbdsDjRlAX2S8";
//		String body = HttpRequest.post(server + "/esbmule/esbmule/receive/queryReceiveTreeList")
//		.cookie(cookie)
//		.header("x-requested-token", token)
//		.body("{\"cond.returntype\":\"\",\"jsonString\":\"{\\\"cond\\\":{}}\"}")
//		.execute().body();
//		//System.out.println(body);
//		JSONArray array = JSONUtil.parseArray(body);
//		JSONArray interfaceList = new JSONArray();
//		for(int i = 0; i < array.size(); i++) {
//			JSONArray children = array.getJSONObject(i).getJSONArray("children");
//			for(int j = 0; j < children.size(); j++) {
//				JSONObject jsonObject = children.getJSONObject(j);
//				String interfaceId = jsonObject.getStr("id");
//				body = HttpRequest.post(server + "/esbmule/esbmule/receiveuser/selectReceiveUserInfoByCond")
//						.cookie(cookie)
//						.header("x-requested-token", token)
//						.body("{\"cond.receiveid\":\""+interfaceId+"\",\"jsonString\":\"{\\\"cond\\\":{}}\"}")
//						.execute().body();
//				String str = "";
//				JSONArray userinfo = JSONUtil.parseObj(body).getJSONArray("receiveUserFromMuleInfos");
//				for(int k = 0; k < userinfo.size(); k++) {
//					str += userinfo.getJSONObject(k).getStr("usercode")+":"+userinfo.getJSONObject(k).getStr("password");
//					if(k!=userinfo.size()-1) {
//						str += ",";
//					}
//				}
//				jsonObject.set("userinfo", str);
//				interfaceList.add(jsonObject);
//			}
//			
//		}
//		exportExcel("E:\\projectManage\\GEDI\\"+(server.contains("ceec")?"集团":"")+"接收接口列表.xlsx", interfaceList);
//		
//		body = HttpRequest.post(server + "/esbmule/esbmule/send/querySendTreeList")
//				.cookie(cookie)
//				.header("x-requested-token", token)
//				.body("{\"cond.returntype\":\"\",\"jsonString\":\"{\\\"cond\\\":{}}\"}")
//				.execute().body();
//		//System.out.println(body);
//		array = JSONUtil.parseArray(body);
//		interfaceList = new JSONArray();
//		for(int i = 0; i < array.size(); i++) {
//			JSONArray children = array.getJSONObject(i).getJSONArray("children");
//			for(int j = 0; j < children.size(); j++) {
//				JSONObject jsonObject = children.getJSONObject(j);
//				String interfaceId = jsonObject.getStr("id");
//				body = HttpRequest.post(server + "/esbmule/esbmule/send/selectSendHeaders")
//						.cookie(cookie)
//						.header("x-requested-token", token)
//						.body("{\"cond.strategyid\":\""+interfaceId+"\",\"jsonString\":\"{\\\"cond\\\":{}}\"}")
//						.execute().body();
//				String str = "";
//				JSONArray userinfo = JSONUtil.parseObj(body).getJSONArray("headers");
//				for(int k = 0; k < userinfo.size(); k++) {
//					str += userinfo.getJSONObject(k).getStr("key")+":"+userinfo.getJSONObject(k).getStr("value");
//					if(k!=userinfo.size()-1) {
//						str += ",";
//					}
//				}
//				jsonObject.set("headinfo", str);
//				interfaceList.add(jsonObject);
//			}
//		}
//		exportExcel("E:\\projectManage\\GEDI\\"+(server.contains("ceec")?"集团":"")+"发送接口列表.xlsx", interfaceList);
		
		
		
		
		
// =========================================APi接口========================================================
		String auth = "dJzAQ4zp:eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjQxNyIsImV4cCI6MTc2NTMzMTE5MCwiaWF0IjoxNzMzNzk1MTkwfQ.i2m_RxfV7VMPT3kErc_eBmiQmBFPLWfpzmRKZLwZQ4M";
		String body = HttpRequest.get("https://api.ceec.net.cn/doc/view/data?spaceId=5PzmK8Jv")
		           .bearerAuth(auth)
		           .execute().body();
		//获取目录
		Map<String, JSONObject> dir = new LinkedHashMap<String, JSONObject>();
		List<JSONObject> dirList = new ArrayList<JSONObject>();
		JSONArray jsonArray = JSONUtil.parseObj(body).getJSONArray("data");
		for(int i = 0; i < jsonArray.size(); i++) {
			JSONObject each = jsonArray.getJSONObject(i);
			if (each.getInt("type") != 3) {
				dirList.add(each);
			}
		}
		for (JSONObject object : dirList) {
			Integer type = object.getInt("type");
			if(type == 1) {
				for (JSONObject o : dirList) {
					if(object.getStr("parentId").equals(o.getStr("id"))) {
						object.set("p1", o.getStr("label"));
						object.set("p2", object.getStr("label"));
					}
				}
				dir.put(object.getStr("id"), object);
			}
			if(type == 2) {
				for (JSONObject o : dirList) {
					if(object.getStr("parentId").equals(o.getStr("id"))) {
						object.set("p2", o.getStr("label"));//资金管理
						for (JSONObject o1 : dirList) {
							if(o.getStr("parentId").equals(o1.getStr("id"))) {
								object.set("p1", o1.getStr("label"));//资金管理
							}
						}
					}
				}
				dir.put(object.getStr("id"), object);
			}
		}
		
		// api列表
		JSONArray result = new JSONArray();
		for(String key : dir.keySet()) {
			JSONObject di = dir.get(key);
			for(int i = 0; i < jsonArray.size(); i++) {
				JSONObject each = jsonArray.getJSONObject(i);
				if (each.getInt("type") == 3 && each.getStr("parentId", "").equals(key) ) {
					each.set("path1", di.getStr("p1"));
					each.set("path2", di.getStr("p2"));
					result.add(each);
				}
			}
		}
		
		// api明细
		JSONArray errorCodeParams = new JSONArray();
		JSONArray requestParams = new JSONArray();
		JSONArray responseParams = new JSONArray();
		JSONArray apiDetail = new JSONArray();
		for(int i = 0; i < result.size(); i++) {
			JSONObject each = result.getJSONObject(i);
			String res = HttpRequest.get("https://api.ceec.net.cn/doc/view/detail?id=" + each.getStr("id"))
					.bearerAuth(auth)
					.execute().body();
			JSONObject obj = JSONUtil.parseObj(res).getJSONObject("data");
			obj.set("description", HtmlUtil.unescape(HtmlUtil.cleanHtmlTag(obj.getStr("description"))));
			obj.set("remark", HtmlUtil.unescape(HtmlUtil.cleanHtmlTag(obj.getStr("remark"))));
			JSONArray envs = obj.getJSONArray("debugEnvs");
			for (int j = 0; j < envs.size(); j++) {
				JSONObject env = envs.getJSONObject(j);
				if("测试环境".equals(env.getStr("name"))) {
					obj.set("testUrl", env.getStr("url")+  "/" +  obj.getStr("url"));
				}else{
					obj.set("prdUrl", env.getStr("url")+  "/" +  obj.getStr("url"));
				}
			}
			if(envs.isEmpty()) {
				obj.set("testUrl", obj.getStr("url"));
				obj.set("prdUrl", obj.getStr("url"));
			}
			
			if(CollUtil.isNotEmpty(obj.getJSONArray("errorCodeParams")))
			    errorCodeParams.addAll(obj.getJSONArray("errorCodeParams"));
			if(CollUtil.isNotEmpty(obj.getJSONArray("requestParams")))
				requestParams.addAll(obj.getJSONArray("requestParams"));
			if(CollUtil.isNotEmpty(obj.getJSONArray("responseParams")))
				responseParams.addAll(obj.getJSONArray("responseParams"));
			
			obj.remove("debugEnvs");
			obj.remove("errorCodeParams");
			obj.remove("requestParams");
			obj.remove("responseParams");
			
			apiDetail.add(obj);
		}
		List<JSONArray> excelList = new ArrayList<JSONArray>() {{
			add(result);
			add(apiDetail);
			add(requestParams);
			add(responseParams);
			add(errorCodeParams);
		}};
		exportExcels("D:/jtdoc3.xlsx", excelList, "api", "apiDetail", "requestParam", "responseParam", "errorcode");
		
		
		
		
		
		
		
		
		
	   
		
	    
	    
	    
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
// =========================================消息推送========================================================		
//		String corpId = "wxb260eb5f2c491d8c";
//		String corpsecret = "AjGBX-la1s5M2FgHRlmOoGxa6YJmCuyJBdruFSWAVo4";
//		String agentId = "1000213";
//		
//		String body = HttpRequest.get("https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid="+corpId+"&corpsecret="+corpsecret).execute().body();
//		System.out.println(body);
//		String token = JSONUtil.parseObj(body).getStr("access_token");
//		Map<String,Object> contentMap = new HashMap<String, Object>();
//		contentMap.put("content", "测试推送111。");
//		Map<String,Object> paramMap = new HashMap<String, Object>();
//		paramMap.put("msgtype", "text");
//		paramMap.put("agentid", agentId);
//		paramMap.put("touser", "ex01438");
//		paramMap.put("text",contentMap);
//		System.out.println(JSONUtil.toJsonStr(paramMap));
//		body = HttpRequest.post("https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token="+token)
//				.contentType(ContentType.FORM_URLENCODED.toString())
//				.body(JSONUtil.toJsonStr(paramMap))
//				.execute().body();
//		System.out.println(body);
		
		
//		body = HttpRequest.get("https://qyapi.weixin.qq.com/cgi-bin/agent/get?access_token="+token+"&agentid="+agentId).execute().body();
//		System.out.println(body);
		
//		System.out.println(DateUtil.now());
		
		

		
	   
		
		
		
	}
	
	
	
	
	
	
	

}
